package com.holic.spring.custom.type;

import graphql.schema.Coercing;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.GraphQLScalarType;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @ClassName CustomScalars
 * @Description
 * @Author Neil
 * @Date 2024/11/15 14:03
 * @Version V1.0
 **/
public final class CustomScalars {

    private CustomScalars() {}

    public static final GraphQLScalarType Date = GraphQLScalarType.newScalar()
            .name("Date")
            .description("Date custom scalar type")
            .coercing(new Coercing<Date, String>() {
                @Override
                public String serialize(Object input) {
                    Date date = (Date) input;
                    return DateFormatUtils.format(date, "yyyy-MM-dd");
                }

                @Override
                public Date parseValue(Object input) {
                    try {
                        return DateUtils.parseDate((String) input, "yyyy-MM-dd");
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public Date parseLiteral(Object input) {
                    if (input instanceof String) {
                        try {
                            return DateUtils.parseDate((String) input, "yyyy-MM-dd");
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    throw new CoercingParseLiteralException("Invalid literal value for Date: " + input);
                }
            })
            .build();

}
